package com.example.book.web;

import com.example.book.pojo.Cart;
import com.example.book.pojo.User;
import com.example.book.service.OrderService;
import com.example.book.service.impl.OrderServiceImpl;
import com.example.book.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description
 * @ClassName OrderServlet
 * @Author 山山大魔王
 * @Date 2021/12/4 18:02
 * @Version 1.0
 */
@WebServlet(name = "OrderServlet",value = "/orderServlet")
public class OrderServlet extends BaseServlet{
    OrderService orderServlet = new OrderServiceImpl();
    /**
     * 生成订单项
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void createOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取Cart购物车对象
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //获取userid
        User loginUser = (User) request.getSession().getAttribute("user");


        if (loginUser == null){
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
            return;
        }

        System.out.println("OrderServlet程序在["+Thread.currentThread().getName()+"]中");
        Integer userId = loginUser.getId();
        //调用orderService.createOrder(Cart,Userid);生成订单
        String orderId = orderServlet.createOrder(cart, userId);

        //保存orderId到request域中
//        request.setAttribute("orderId", orderId);
        //请求转发到/pages/cart/checkout.jsp
//        request.getRequestDispatcher("/pages/cart/checkout.jsp").forward(request, response);
        //保存orderId到Session中
        request.getSession().setAttribute("orderId", orderId);
        //重定向到request.getContextPath()/pages/cart/checkout.jsp
        response.sendRedirect(request.getContextPath()+"/pages/cart/checkout.jsp");
    }
}
